// The NSpring Framework for .NET
// Copyright (c) 2003, Jeffrey Varszegi
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
// 
// - Redistributions of source code must retain the above copyright notice, this 
// list of conditions and the following disclaimer.
// 
// - Redistributions in binary form must reproduce the above copyright notice, this 
// list of conditions and the following disclaimer in the documentation and/or other 
// materials provided with the distribution.
// 
// - Neither the name of the NSpring project nor the names of its contributors may 
// be used to endorse or promote products derived from this software without 
// specific prior written permission from the copyright owner.
// 
// - No product derived from this software may be called "NSpring", nor may 
// "NSpring" appear in the name of such a product, without specific prior written 
// permission from the copyright owner.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGE. 

namespace NSpring.Logging.EventFormatters {

using System;
using System.Text;

using NSpring.Logging;
using NSpring.Logging.Common;
using NSpring.Logging.Common.Pattern;
using NSpring.Logging.Common.Pattern.Patterns;
using NSpring.Logging.DataFormatters;

/// <summary>
/// An EventFormatter implementation that formats events according to a pattern.
/// See the documentation of the pattern formatting language for more details.
/// </summary>
public sealed class PatternEventFormatter : EventFormatter {
    private static string timeZone                      = Constants.ISO_8601_TIME_ZONE;
    private static string daylightSavingsTimeZone       = Constants.ISO_8601_DAYLIGHT_SAVINGS_TIME_ZONE;
    private static string[] monthNames                  = Constants.MonthNames;
    private static string[] monthShortNames             = Constants.MonthShortNames;
    private static string[] weekdayNames                = Constants.WeekdayNames;
    private static string[] weekdayShortNames           = Constants.WeekdayShortNames;
    private static string[] yearStrings                 = Constants.YearStrings;
    private static string[] dateStrings                 = Constants.DateStrings;
    private static string[] millisecondStrings          = Constants.MillisecondStrings;

    private const char COLON_CHAR                       = ':';
    private const char HYPHEN_CHAR                      = '-';
    private const char PERIOD_CHAR                      = '.';
    private const char SPACE_CHAR                       = ' ';

    
    private const string BLANK_STRING                   = "";
    private const char SPACE                            = ' ';

    private const int DEFAULT_BUFFER_SIZE               = 64;
    private const int SAMPLE_FREQUENCY                  = 5;
    private const int BUFFER_SIZE_RESET_FREQUENCY       = 1500;

    private int bufferSize                              = DEFAULT_BUFFER_SIZE;
    private int sampleCount                             = 0;
    private int sampleTickCount                         = 0;
    
    private Token[] tokens;
    private string patternSource;
    
    private PatternEventFormatter() {}
    
    /// <summary>
    /// Constructs a new instance using the specified pattern
    /// </summary>
    /// <param name="_pattern">The pattern to use</param>
    public PatternEventFormatter(string _pattern) {
        if (_pattern == null) {
            throw new ArgumentNullException();
        }
        dataFormatter = new FlatDataFormatter();
        patternSource = _pattern;
        tokens = (new PatternParser(true, true, false, true, true)).Parse(patternSource + suffix);
    }

    protected override bool UpdateSuffix(string _newSuffix) {
        tokens = (new PatternParser(true, true, false, true, true)).Parse(patternSource + suffix);
        return true;
    }

    
    /// <summary>
    /// Constructs a string representation of the indicated event
    /// </summary>
    /// <param name="_event">The event to format</param>
    /// <returns>A string representation of the event</returns>
    public override string Format(Event _event) {
        StringBuilder sb = new StringBuilder(bufferSize);
        Token token;
        for(int x = 0; x < tokens.Length; x++) {
            token = tokens[x];
            switch (token.Type) {
                case TokenType.Text             :
                case TokenType.Separator        : {
                    sb.Append(token.Text);
                    break;
                }
                case TokenType.ContextProperty  : 
                case TokenType.EventProperty    : {
                    token.Format(_event, sb);
                    break;
                }
                case TokenType.Data             : {
                    dataFormatter.Format(_event.Data, sb);
                    break;
                }
                default                         : {
                    sb.Append(token.Format(_event));
                    break;
                }
            }
        }

        sb.Append(suffix);
        
        sampleCount++;
        if (sampleCount == SAMPLE_FREQUENCY) {
            int length = sb.Length;
            if (length > bufferSize) {
                bufferSize = length;
            }
            sampleCount = 0;
            
            sampleTickCount++;
            if (sampleTickCount >= BUFFER_SIZE_RESET_FREQUENCY) {
                bufferSize = DEFAULT_BUFFER_SIZE;
                sampleTickCount = 0;
            }
        }
        
        return sb.ToString();
    }
        
    /// <summary>
    /// Gets and sets the pattern used by the formatter.  See the documentation of 
    /// the pattern language for more details
    /// </summary>
    public string Pattern {
        get {
            return patternSource;
        }
        set {
            if (value == null) {
                throw new ArgumentNullException();
            }
            lock (monitor) {
                Token[] newTokens = (new PatternParser(true, true, false, true, true)).Parse(value + suffix);
                tokens = newTokens;
                patternSource = value;
            }
        }
    }
    
    public override string GetEventListHeader() {
        return null;
    }
    public override string GetEventListFooter() {
        return null;
    }
    
    
}

}
